/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.mina.filter;

import java.util.Timer;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;


/**
 * Throttle the writing and only write one char at a line
 */
public class ResponseThrottlingFilter extends IoFilterAdapter {

    private long delayTime = 500;

    public synchronized void setDelayTime(long delayTime) {
        this.delayTime = delayTime;
    }

    @Override
    public void filterWrite(NextFilter arg0, IoSession arg1, WriteRequest arg2)
            throws Exception {

        if (arg2.getMessage() instanceof String) {

            String response = (String) arg2.getMessage();

            Timer timer = new Timer();

            for (int i = 0; i < response.length(); i++) {

                // Schedule the write
                timer.schedule(new ThrottlingWriteTimerTask(arg0, arg1,
                        new WriteRequest(response.charAt(i))), (i + 1)
                        * delayTime);
            }
        } else {
            arg0.filterWrite(arg1, arg2);
        }
    }
}
